package org.meluk.billboard.beans.user;

import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.meluk.billboard.jpa.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String principal = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        Session session = getSessionFactory().getCurrentSession();
        User user = User.findByNameAndPassword(session, principal, password);
        if (user != null) {
            UserDetails userDetails = new UserDetails(user);
            return new UsernamePasswordAuthenticationToken(userDetails,
                    password,
                    userDetails.getAuthorities());
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> type) {
        return type.equals(UsernamePasswordAuthenticationToken.class);
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
